/**
 * 清除无效的路由或还原注释
 * 用法示例 babel-node clearInvalidRoute clear 清除 babel-node clearInvalidRoute back
 */
const fs = require('fs');
const path = require('path');
const routerObject = require('./src/routes/showMenu').default;
const routePath = path.resolve(__dirname,'./src/routes');
const menuPath = path.resolve(__dirname,'./src/routes/menuRoute.js');

getFunction();

function getFunction() {
  switch (process.argv[2]) {
    case 'clear':
      clear();
      break;
    case 'back':
      back();
      break;
    default:
      console.log('请输入正确的命令');
      break;
  }
}

//清空无效路由应用
function clear() {
  let files = fs.readdirSync(routePath);
  files.forEach(fileName => {
    let file = path.join(routePath,fileName);
    let stats = fs.statSync(file);
    if (stats.isDirectory()) {
      handleRouteFile(file);
    }
  });
  handleMenu();
  // routerObject.list
}

function handleRouteFile(file) {
  let routeFile = fs.readdirSync(file);
  routeFile.forEach(routeName => {
    let routeFile = path.join(file,routeName);//normal 或 admin的文件
    let stats = fs.statSync(routeFile);
    if (stats.isFile()) {
      let content = fs.readFileSync(routeFile,'utf-8');
      let temp = routeFile.split('/');
      temp.splice(0,temp.length - 3);
      let res = temp.join('/').replace('.js','');
      // const routerObject = require(`./src/${res}`).default;
      let key = getKey(content);
      let invalidKey = [];
      let isContainer = false;
      routerObject.list.map(item => {
        if(item.key === key[0]){
          isContainer = true;
          if(key.length > 1){
            key.map((id,index) => {
              if(index !== 0){
                item.list.indexOf(id) < 0 && (invalidKey.push(id));
              }
            });
          }
        }
      });
      if(invalidKey.length > 0){
        invalidKey.map(item => {
          content = removeSubKey(content,item);
        });
        content = removeImport(content);
        fs.writeFileSync(routeFile,content);
      };
      if(!isContainer){
        let menu = fs.readFileSync(menuPath,'utf-8');
        let regExp = new RegExp(`import ([a-zA-Z]+?) from (\'|")${res}('|")(\\s)*(;)?(//([^\n])*)?`,'ig');
        menu = menu.replace(regExp,'');
        fs.writeFileSync(menuPath,menu);
      };
    }
  })
}

function getKey(str){
  let regNote = new RegExp("((//[^\n]+[\n])|(/\\*([.\n\\s\\S]+?)\\*/)|(<!--([.\n\\s\\S]+?)-->))","mg");
  str = str.replace(regNote,'');
  let reg = new RegExp('key(\\s)*:(\\s)*(\'|")([^\'"]*)(\'|")','g');
  let arr = [];
  str.replace(reg,(target,$1,$2,$3,$4) => {
    arr.push($4);
  });
  let childrenReg = new RegExp('children(\\s)*:(\\s)*{(([^a-zA-Z]*)([a-zA-Z]+)(\\s)*:(\\s)*{([.\n\\s\\S]+?)}(,)?)*([^}]*)}','g');
  let temp = [];
  str.replace(childrenReg,(target) => {
    target.replace(reg,(goal,$1,$2,$3,$4) => {
      temp.push($4);
    })
  });
  let obj = {};
  arr.forEach(item => obj[item] = item);
  temp.forEach(item => delete obj[item]);
  return Object.keys(obj);
}

function removeSubKey(str,key) {
  let regExp = new RegExp(`{([^{]+?)key(\\s)*:(\\s)*('|")${key}('|")([^{}]*)({(([^a-zA-Z]*)([a-zA-Z]+)(\\s)*:(\\s)*{([.\n\\s\\S]+?)}(,)?)*([^}]*)})?([^{}]*)}(,)?`,'g');
  str = str.replace(regExp,'');
  return str;
}

function removeImport(str) {
  let reg = new RegExp('import(\\s)*([a-zA-Z]+)(\\s)*from(\\s)*(\'|")([^\'"]+)(\'|")(;)?\n','mg');
  str = str.replace(reg,(target,$1,$2) => {
    let componentsReg = new RegExp(`components(\\s)*:(\\s)*${$2}`,'g');
    if(!componentsReg.test(str)){
      target = '';
    }
    return target;
  });
  return str;
}

function handleMenu() {
  let content = fs.readFileSync(menuPath,'utf-8');
  let reg = new RegExp('const menu = \\[([^\\]]+)\\]','g');
  content = content.replace(reg,(target,$1) => {
    let comReg = new RegExp('([a-zA-Z]+)(\\s)*(,)?(\\s)*(//[^\n]+[\n])?','g');
    $1 = $1.replace(comReg,(tar,f1) => {
      let importReg = new RegExp(`import(\\s)*${f1}(\\s)*from`,'g');
      if(!importReg.test(content)){
        tar = '';
      }
      return tar;
    });
    target = `const menu = [${$1}]`;
    return target;
  });
  fs.writeFileSync(menuPath,content);
}

//还原无效路由
function back() {

}
